﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;

namespace YouTubeDownloadExtension
{
    public sealed class VideoSourceBuilder
    {
        private const string InfoPagePrefix = "http://youtube.com/get_video_info?video_id=";

        private readonly string videoId;
        private IEnumerable<VideoSource> sources;

        public VideoSourceBuilder(string videoId)
        {
            if (videoId == null)
                throw new ArgumentNullException("videoId");
            if (videoId == string.Empty)
                throw new ArgumentException("Empty video ID.", "videoId");
            this.videoId = videoId;
        }

        public IEnumerable<VideoSource> GetSources()
        {
            if (sources == null)
                throw new InvalidOperationException("Video sources haven't been built yet.");
            return sources;
        }

        public void BuildSources()
        {
            var videoInfo = LoadVideoInfo();
            var uris = GetStreamUrisFromVideoInfo(videoInfo);
            sources = uris.Select(VideoSource.FromUri);
        }

        private string LoadVideoInfo()
        {
            using (var client = new WebClient())
            {
                return client.DownloadString(InfoPagePrefix + videoId);
            }
        }     

        private static IEnumerable<Uri> GetStreamUrisFromVideoInfo(string videoInfo)
        {            
            var scraper = new VideoInfoScraper(videoInfo);
            scraper.ExtractData();
            return scraper.GetUris();
        }                   
    }
}
